<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关的参数" type="warning"></el-alert>
      <el-row style="line-height:37px">
        <el-col :span="3">
          <span>选择商品分类:</span>
        </el-col>
        <el-col :span="4">
          <!-- 商品的分类的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedCatesKeys"
            :options="catesLists"
            :props="paramsCatesProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 页签 tab -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addParamsdialogVisible = true"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handeClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-deit"
                  @click="editmanyTableData(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性对话框 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addParamsdialogVisible = true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handeClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-deit"
                  @click="editmanyTableData(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText "
      :visible.sync="addParamsdialogVisible"
      width="50%"
      @close="addParamsGialogClose"
    >
      <!-- 添加对话框的表单 -->
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText "
      :visible.sync="editParamsdialogVisible"
      width="50%"
      @close="editParamsGialogClose"
    >
      <!-- 修改对话框的表单 -->
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有分类的数据
      catesLists: [],
      // 级联选择双向绑定的数组
      selectedCatesKeys: [],
      // props属性设置
      paramsCatesProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 被激活的页签名称
      activeName: 'many',
      // 动态表格数据
      manyTableData: [],
      // 静态表格数据
      onlyTableData: [],
      // 显示与隐藏添加参数对话框
      addParamsdialogVisible: false,
      // 添加参数的对话框表单的数据对象
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数的对话框表单验证
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名', trigger: 'blur' }
        ]
      },
      // 修改对话框的显示与隐藏
      editParamsdialogVisible: false,
      // 修改对话框的表单数据对象
      editParamsForm: {},
      // 修改对话框的表单数据的验证
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getCatesLists () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类信息失败')
      }
      this.catesLists = res.data
      console.log(this.catesLists)
    },
    // 级联选择选中的时候被触发
    async handleChange () {
      this.getParamsData()
    },
    // 页签被点击后的处理函数
    handleTabClick () {
      this.getParamsData()
    },
    // 获取参数列表数据
    async getParamsData () {
      // 判断是否选中的是三级分类
      if (this.selectedCatesKeys.length !== 3) {
        // 不是三级分类
        this.selectedCatesKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }

      // 根据不同的id，和不同的面板，获取不同的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本的显示与隐藏
        item.inputVisible = false
        // 文本输入框
        item.inputValue = ''
      })

      console.log(res.data)

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 关闭添加参数对话框处理函数
    addParamsGialogClose () {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 确定提交添加参数
    addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('更新参数失败')
        }
        this.$message.success('更新参数成功')

        this.addParamsdialogVisible = false
        this.getParamsData()
      })
    },
    // 点击编辑按钮事件处理函数
    async editmanyTableData (attrId) {
      // 查询当前参数信息
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }

      this.editParamsForm = res.data

      this.editParamsdialogVisible = true
    },
    // 确定提交修改表单处理函数
    editParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('更新参数失败')
        }
        this.$message.success('更新参数成功')
        this.getParamsData()
        this.editParamsdialogVisible = false
      })
    },
    // 关闭修改对话框的事件处理函数
    editParamsGialogClose () {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 根据id删除相关的参数
    async removeParams (attrId) {
      const confirmResult = await this.$messageBox
        .confirm('此操作将永久删除此参数？', '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getParamsData()
    },
    // 当输入框和摁下 enter 时候触发这个事件处理函数
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 当输入框的值合法，时才执行下面的代码
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      // 保存到数据库
      this.saveAttrVals(row)
    },
    // 保存到数据库操作
    async saveAttrVals (row) {
      // 把相关的参数保存到数据库中
      const {
        data: res
      } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.errot('更新参数失败')
      }
      this.$message.success('更新参数成功')
    },
    // 当点击按钮时触发这个事件处理函数
    showInput (row) {
      row.inputVisible = true
      // $nextTick 方法作用，当页面上的元素被渲染完成后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除对应的可选项
    handeClose (i, row) {
      row.attr_vals.splice(i, 1)
      // 保存到数据库
      this.saveAttrVals(row)
    }
  },
  created () {
    this.getCatesLists()
  },
  computed: {
    isBtnDisabled () {
      if (this.selectedCatesKeys.length !== 3) {
        return true
      }
      return false
    },
    // 被选中的三级id
    cateId () {
      if (this.selectedCatesKeys.length === 3) {
        return this.selectedCatesKeys[2]
      }

      return null
    },
    // 添加对话框title
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin: 20px 0;
}

.el-button {
  margin: 15px 0;
}

.el-tag {
  margin: 5px 5px;
}
.input-new-tag {
  width: 150px;
}
</style>
